<script lang="ts" setup>
import type { BaseEntity, ResultList } from '@/index.d';
import { urls, api } from '@/index';
import type { CascaderOption, CascaderProps } from 'element-plus';
import { useRequest } from 'vue-request';

const props = defineProps({
  clearable: {
    type: Boolean,
    default: false
  }
});

const current = defineModel('current', {
  default: 0
});

const cascaderProps: CascaderProps = {
  expandTrigger: 'hover', //当鼠标放置时展开菜单
  checkStrictly: true, //可以选择各个节点的值
  label: 'label', //用来建立label显示的内容
  value: 'id', //用来定义下来值对应的字段
  emitPath: false //false只传递自节点的值，true传递全部链条的值
};

const getDepatmentCascader = async <T extends BaseEntity>() => {
  try {
    const res = await api({
      method: 'get',
      url: `${urls.department}/getCascade`
    });

    if (res.status === 200) {
      const resData: ResultList<T> = res.data;
      if (resData.status) {
        return resData.body;
      } else {
        ElMessage({
          message: resData.msg,
          type: resData.type
        });
      }
    } else {
      ElMessage.error(res.statusText);
    }
  } catch (error) {
    ElMessage.error('获取失败，错误信息是：' + error);
    return false;
  }
};

const getDepartmentCascader = () => getDepatmentCascader();

const { data } = useRequest(getDepartmentCascader);

const departmentCascaderData = computed(() => data.value as CascaderOption[]);
</script>
<template>
  <el-cascader
    v-model="current"
    :options="departmentCascaderData"
    :props="cascaderProps"
    :show-all-levels="false"
    filterable
    placeholder="请选择部门"
    :clearable="props.clearable"
    v-bind="$attrs"
  />
</template>
<style lang="scss" scoped></style>
